/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.projectdarkstar.ai.tree.test;

import com.projectdarkstar.ai.tree.InOrderTreeNode;
import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.AppListener;
import com.sun.sgs.app.ClientSession;
import com.sun.sgs.app.ClientSessionListener;
import com.sun.sgs.app.ManagedObject;
import java.io.Serializable;
import java.util.Properties;

/**
 *
 * @author Jeff Kesselman
 */
public class InOrderWordJumbler implements AppListener, ManagedObject, 
        Serializable{
        
    public static final long SerialVersionUID=1L;
    
    public void initialize(Properties arg0) {
        new WordJumblerNode(null,"","OBama").evaluate();
    }

    public ClientSessionListener loggedIn(ClientSession arg0) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    private static class WordJumblerNode extends InOrderTreeNode {
        String myJumble;
        String remainingLetters;
        int currentChildCounter=0;
        
        public WordJumblerNode(WordJumblerNode parent,String myJumble, 
                String remainingLetters){
            super(parent);
            this.myJumble = myJumble;
            this.remainingLetters = remainingLetters;
        }
        
        @Override
        protected void preDescentEvaluation() {
            if (myJumble!=null){
                System.out.println(myJumble);
            }
        }

        @Override
        protected InOrderTreeNode nextChild(Object object) {
            AppContext.getDataManager().markForUpdate(this);
            if (currentChildCounter<remainingLetters.length()){
               WordJumblerNode child = new WordJumblerNode(this,
                        myJumble+remainingLetters.charAt(currentChildCounter),
                        remainingLetters.substring(0,currentChildCounter)+
                        remainingLetters.substring(currentChildCounter+1));
               currentChildCounter++;
               return child;
            } else {
                return null; // end of children
            }
        }

        @Override
        protected void postDescentEvaluation() {
            // cleanup, only leave root node remaining cause we didnt create it.
            if (!isRoot()){
                AppContext.getDataManager().removeObject(this);
            } else {
                System.out.println("Done!");
            }
        }
        
    }

}
